<?php

declare(strict_types=1);

namespace App\Utils;

use EasyWeChat\MiniApp\Application;

use Hyperf\Context\ApplicationContext;
use Hyperf\HttpServer\Contract\RequestInterface;

use function Hyperf\Config\config;

class WechatMiniApp
{
    private Application $app;

    public function __construct()
    {
        $this->app = new Application(config('wechat.mini_app'));
        $request = ApplicationContext::getContainer()->get(RequestInterface::class);
        $this->app->setRequest($request);
    }

    /**
     * 小程序登录
     * @link https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
     * @param string $code
     * @return array
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\DecodingExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
     */
    public function codeToSession(string $code): array
    {
        return $this->app->getUtils()->codeToSession($code);
    }

    /**
     * 获取不限制的小程序码
     * 分钟频率受限（5000次/分钟）
     * @link https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/qrcode-link/qr-code/getUnlimitedQRCode.html
     * @param string $scene
     * @param string $filename
     * @return void
     * @throws \EasyWeChat\Kernel\Exceptions\BadResponseException
     * @throws \Symfony\Contracts\HttpClient\Exception\ClientExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\RedirectionExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\ServerExceptionInterface
     * @throws \Symfony\Contracts\HttpClient\Exception\TransportExceptionInterface
     */
    public function getUnlimitedQRCode(string $scene, string $filename): void
    {
        $dir = dirname($filename);
        if (!is_dir($dir)) {
            mkdir($dir);
        }

        $response = $this->app->getClient()->postJson('/wxa/getwxacodeunlimit', [
            'scene' => $scene,
            'page' => 'pages/index/index',
            'width' => 430,
            'check_path' => false,
            'env_version' => config('app_env') === 'prod' ? 'release' : 'trial',
        ]);

        $response->saveAs($filename);
    }
}
